import React,{useEffect,useRef,useState} from 'react'
import './ColorBar.css'


function ColorBar(props) {
    const canvasRef = useRef(null) ;
    //加载style，渲染canvas
    useEffect(() => {
        const canvas = canvasRef.current ;
        const context = canvas.getContext('2d') ;
        let colors = [] ;
        for(var ic =0 ; ic < props.styleObj.colors.length ; ++ ic )
        {
            let clr1 = props.styleObj.colors[ic] ;
            let cstr = 'rgba(' 
                + clr1.r.toString() + ','
                + clr1.g.toString() + ','
                + clr1.b.toString() + ','
                + (clr1.a/255.0).toString()
                + ')'
            colors.push(cstr) ;
        }
        let wid = canvas.width ;
        let hei = canvas.height ;
        drawLinearStyleOnCanvas(context,colors,wid,hei) ;
    }, [props.styleObj])


    //生成透明棋盘格背景
    const checkerBoardPattern = (() => {
        const size = 8;
        const canvas = document.createElement('canvas');
        canvas.width = size * 2;
        canvas.height = size * 2;
        const g = canvas.getContext('2d');
        g.fillStyle = 'rgb(200, 200, 200)';
        g.fillRect(0, 0, size, size);
        g.fillRect(size, size, size, size);
        g.fillStyle = 'rgb(240, 240, 240)';
        g.fillRect(0, size, size, size);
        g.fillRect(size, 0, size, size);
        return g.createPattern(canvas, 'repeat');
      })();


    //绘制线性渐变色
    const drawLinearStyleOnCanvas = (
        ctx,
        colors,//should be RGBA
        width,
        height,
      ) => {
        ctx.fillStyle = checkerBoardPattern;
        ctx.fillRect(0, 0, width, height);
        if (colors) {
          const bins = colors.length - 1;
          const binWidth = width / bins;
          const drawWidth = Math.ceil(binWidth);
          for(var icolor=0;icolor<bins;++ icolor)
          {
              let color1 = colors[icolor];
              let color2 = colors[icolor+1] ;
              var gradient1=ctx.createLinearGradient( drawWidth*icolor,0,drawWidth*(icolor+1),0);//渐变颜色路径
              gradient1.addColorStop(0,color1);
              gradient1.addColorStop(1,color2);
              ctx.fillStyle = gradient1;
              ctx.fillRect( drawWidth*icolor , 0 , drawWidth, height);
          }
        }
    }

    return (
        <canvas className='ColorBarCanvas' ref={canvasRef} />
    )
}

export default ColorBar
